package api

import (
	"encoding/json"
	"net/http"
    "strconv"

	"sipserver/device"
	"sipserver/sip"
	//"encoding/xml"
	//"fmt"
)

var globalSIPServer *sip.SIPServer

func StartAPIServer(addr string, sipServer *sip.SIPServer) {
	globalSIPServer = sipServer
	http.HandleFunc("/ptz/control", PTZControlHandler)
	http.HandleFunc("/play", PlayHandler)
    http.HandleFunc("/stop", StopHandler)
	http.HandleFunc("/list_devices", GetUserList)
    http.HandleFunc("/delete_devices", DeleteUserHandler)
	http.HandleFunc("/start-broadcast", handleStartBroadcast)
    http.HandleFunc("/stop-broadcast", handleStopBroadcast)
	http.HandleFunc("/take-picture", TakePicture)
	http.HandleFunc("/take-history", TakeHistory)
	http.HandleFunc("/take-message", MessageQuery)
	
	
	http.ListenAndServe(addr, nil)
}

func PTZControlHandler(w http.ResponseWriter, r *http.Request) {
	deviceID := r.URL.Query().Get("device_id")
	direction := r.URL.Query().Get("direction")
	//speed := r.URL.Query().Get("speed")

	// ptzControl := ptz.PTZControl{DeviceID: deviceID}
	// ptzControl.Move(direction, 0) // 简化处理，忽略速度

    var xmlBody string
    switch direction {
        case "left": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F010280808037</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "top": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F01088080803D</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "right": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F010180808036</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "buttom": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F010480808039</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "stop": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F0100000000B5</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "big": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F011080808045</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "small": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F012080808055</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "focuson": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F014280808077</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "focusoff": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F014180808076</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "lightbig": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F01488080807D</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
        case "lightsmall": xmlBody = "<?xml version=\"1.0\" encoding=\"GB2312\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>10005</SN>\n<DeviceID>"+deviceID+"</DeviceID>\n<PTZCmd>A50F014480808079</PTZCmd>\n<Info>\n<ControlPriority>5</ControlPriority>\n</Info>\n</Control>"
    }

	// err := globalSIPServer.PTZControl("34020000002000000001", "34020000001320000001", 
	// 	"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Control>\n<CmdType>DeviceControl</CmdType>\n<SN>2</SN>\n<DeviceID>34020000001320000001</DeviceID>\n<PTZCmd>A50F0102FF0020</PTZCmd>\n</Control>", false)
	// if err != nil {
	// 	fmt.Println("PTZ control failed:", err)
	// }

    // err := globalSIPServer.PTZControl("34020000002000000001", deviceID, xmlBody, false)
    // if err != nil {
    //     fmt.Println("PTZ control failed:", err)
    // }

    go globalSIPServer.PTZControl(deviceID, xmlBody, false)

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("PTZ control successfully"))
    return
}

func PlayHandler(w http.ResponseWriter, r *http.Request) {
    // 从请求参数中获取设备 ID 和媒体 URL
    deviceID := r.URL.Query().Get("device_id")
    if deviceID == "" {
        w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte("device_id is required"))
        return
    }

	// err := globalSIPServer.Options(deviceID)
	// if err != nil {
    //     w.WriteHeader(http.StatusInternalServerError)
    //     w.Write([]byte(fmt.Sprintf("Failed to start playback: %v", err)))
    //     return
    // }

    // 构建 SDP 媒体描述
    mediaURL := `v=0
o=34020000001320000001 0 0 IN IP4 192.168.1.213
s=Play
u=34020000001320000001:0
c=IN IP4 192.168.1.213
t=0 0
m=video 15060 TCP/RTP/AVP 96 97 98
a=recvonly
a=setup:passive
a=connection:new
a=rtpmap:96 PS/90000
a=rtpmap:97 MPEG4/90000
a=rtpmap:98 H264/90000
y=0200000001
`

    // 调用 Invite 方法发起音视频播放请求
    // err := globalSIPServer.Invite(deviceID, mediaURL)
    // if err != nil {
    //     w.WriteHeader(http.StatusInternalServerError)
    //     w.Write([]byte(fmt.Sprintf("Failed to start playback: %v", err)))
    //     return
    // }
    go globalSIPServer.Invite(deviceID, mediaURL)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Playback started"))
    return
}

//StopStream
func StopHandler(w http.ResponseWriter, r *http.Request) {
    // 从请求参数中获取设备 ID 和媒体 URL
    deviceID := r.URL.Query().Get("device_id")
    if deviceID == "" {
        w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte("device_id is required"))
        return
    }

	// err := globalSIPServer.Options(deviceID)
	// if err != nil {
    //     w.WriteHeader(http.StatusInternalServerError)
    //     w.Write([]byte(fmt.Sprintf("Failed to start playback: %v", err)))
    //     return
    // }

    // 构建 SDP 媒体描述
    mediaURL := `v=0
o=34020000001320000001 3651 3651 IN IP4 192.168.1.100
s=play
c=IN IP4 192.168.1.100
t=0 0
m=video 5004 RTP/AVP 96
a=sendonly
a=rtpmap:96 PS/90000
a=username:34020000001320000001
a=password:123456
a=filesize:0
y=0200000001
f=
`

    // 调用 Invite 方法发起音视频播放请求
    // err := globalSIPServer.StopStream(deviceID, mediaURL)
    // if err != nil {
    //     w.WriteHeader(http.StatusInternalServerError)
    //     w.Write([]byte(fmt.Sprintf("Failed to start playback: %v", err)))
    //     return
    // }
    go globalSIPServer.StopStream(deviceID, mediaURL)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Playback stop"))
}

// handleStartBroadcast 处理启动语音广播的 HTTP 请求
func handleStartBroadcast(w http.ResponseWriter, r *http.Request) {
    deviceID := r.URL.Query().Get("deviceID")
    if deviceID == "" {
        http.Error(w, "deviceID is required", http.StatusBadRequest)
        return
    }

    mediaURL := `v=0
o=- 0 0 IN IP4 192.168.1.100
s=Broadcast
c=IN IP4 192.168.1.100
t=0 0
m=audio 5004 RTP/AVP 8
a=rtpmap:8 PCMA/8000`

    // err := globalSIPServer.VoiceInvite(deviceID, mediaURL)
    // if err != nil {
    //     http.Error(w, fmt.Sprintf("Failed to start broadcast: %v", err), http.StatusInternalServerError)
    //     return
    // }
    go globalSIPServer.VoiceInvite(deviceID, mediaURL)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Broadcast started successfully"))
}

// handleStopBroadcast 处理停止语音广播的 HTTP 请求
func handleStopBroadcast(w http.ResponseWriter, r *http.Request) {
    deviceID := r.URL.Query().Get("deviceID")
    if deviceID == "" {
        http.Error(w, "deviceID is required", http.StatusBadRequest)
        return
    }

    // err := globalSIPServer.Bye(deviceID)
    // if err != nil {
    //     http.Error(w, fmt.Sprintf("Failed to stop broadcast: %v", err), http.StatusInternalServerError)
    //     return
    // }
    go globalSIPServer.Bye(deviceID)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Broadcast stopped successfully"))
}

func TakePicture(w http.ResponseWriter, r *http.Request) {
    deviceID := r.URL.Query().Get("deviceID")
    if deviceID == "" {
        http.Error(w, "deviceID is required", http.StatusBadRequest)
        return
    }

    // err := globalSIPServer.TakePicture(deviceID)
    // if err != nil {
    //     http.Error(w, fmt.Sprintf("Failed to stop broadcast: %v", err), http.StatusInternalServerError)
    //     return
    // }
    go globalSIPServer.TakePicture(deviceID)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("TakePicture successfully"))
}

// 处理查询请求
func MessageQuery(w http.ResponseWriter, r *http.Request) {
    deviceID := r.URL.Query().Get("deviceID")
    if deviceID == "" {
        http.Error(w, "deviceID is required", http.StatusBadRequest)
        return
    }

    cmdType := r.URL.Query().Get("cmdType")
    if cmdType == "" {
        http.Error(w, "cmdType is required", http.StatusBadRequest)
        return
    }

    var xmlBody string
    switch cmdType {
    case "DeviceInfoQuery":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Control><CmdType>DeviceInfoQuery</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Control>`
    case "DeviceInfo":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>DeviceInfo</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
    case "DeviceStatus":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>DeviceStatus</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
    case "DeviceConfig":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>DeviceConfig</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
    case "PresetPosition":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>PresetPosition</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
    case "GuardPosition":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>GuardPosition</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
    case "CruiseTrackList":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>CruiseTrackList</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
	case "CruiseTrackQuery":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>CruiseTrackQuery</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
	case "PTZAccurateStatusQuery":
        xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>PTZAccurateStatusQuery</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
	case "MemoryCardStatusQuery":
		xmlBody = `<?xml version="1.0" encoding="UTF-8"?><Query><CmdType>MemoryCardStatusQuery</CmdType><SN>123456</SN><DeviceID>` + deviceID + `</DeviceID></Query>`
    default:
        http.Error(w, "unsupported cmdType", http.StatusBadRequest)
        return
    }

    // response, err := globalSIPServer.SendMessageRequest(deviceID, cmdType, xmlBody)
    // if err != nil {
    //     http.Error(w, fmt.Sprintf("Failed to query device information: %v", err), http.StatusInternalServerError)
    //     return
    // }

    go globalSIPServer.SendMessageRequest(deviceID, cmdType, xmlBody)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("TakeMessage successfully"))

    // var resp interface{}
    // switch cmdType {
    // case "DeviceInfoQuery":
    //     resp, err = globalSIPServer.ParseDeviceInfoResponse(response)
    // case "DeviceInfo":
    //     resp, err = globalSIPServer.ParseFrontEndDeviceInfoResponse(response)
    // case "DeviceStatus":
    //     resp, err = globalSIPServer.ParseFrontEndDeviceStatusResponse(response)
    // case "DeviceConfig":
    //     resp, err = globalSIPServer.ParseDeviceConfigResponse(response)
    // case "PresetPosition":
    //     resp, err = globalSIPServer.ParsePresetPositionResponse(response)
    // case "GuardPosition":
    //     resp, err = globalSIPServer.ParseGuardPositionResponse(response)
    // case "CruiseTrackList":
    //     resp, err = globalSIPServer.ParseCruiseTrackListResponse(response)
	// case "CruiseTrackQuery":
    //     resp, err = globalSIPServer.ParseCruiseTrackQueryResponse(response)
	// case "PTZAccurateStatusQuery":
    //     resp, err = globalSIPServer.ParsePTZAccurateStatusQueryResponse(response)
	// case "MemoryCardStatusQuery":
    //     resp, err = globalSIPServer.ParseMemoryCardStatusQueryResponse(response)
    // }

    // if err != nil {
    //     http.Error(w, fmt.Sprintf("Failed to parse response: %v", err), http.StatusInternalServerError)
    //     return
    // }

    // w.Header().Set("Content-Type", "application/json")
    // w.WriteHeader(http.StatusOK)
    // b, _ := xml.MarshalIndent(resp, "", "  ")
    // w.Write(b)
}


func TakeHistory(w http.ResponseWriter, r *http.Request) {
    deviceID := r.URL.Query().Get("deviceID")
    if deviceID == "" {
        http.Error(w, "deviceID is required", http.StatusBadRequest)
        return
    }

	startTime := r.URL.Query().Get("startTime")
	endTime := r.URL.Query().Get("endTime")

    // err := globalSIPServer.HistoryInvite(deviceID,startTime,endTime)
    // if err != nil {
    //     http.Error(w, fmt.Sprintf("Failed to stop broadcast: %v", err), http.StatusInternalServerError)
    //     return
    // }
    globalSIPServer.HistoryInvite(deviceID,startTime,endTime)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("TakePicture successfully"))
}


func ListDevicesHandler(w http.ResponseWriter, r *http.Request) {
	devices := device.ListDevices()
	json.NewEncoder(w).Encode(devices)
}

func GetUserList(w http.ResponseWriter, r *http.Request) {
    // 设置响应头为 JSON 格式
    w.Header().Set("Content-Type", "application/json")

    // 调用模型层获取用户列表
    data := device.GetDeviceList()

    //将数据编码为 JSON 并发送响应
    err := json.NewEncoder(w).Encode(map[string]interface{}{
        "message": data,
    })
    if err != nil {
        // 处理 JSON 编码错误
        http.Error(w, "Failed to encode JSON", http.StatusInternalServerError)
        return
    }
}

// DeleteUserHandler 处理删除用户的请求
func DeleteUserHandler(w http.ResponseWriter, r *http.Request) {
    // 设置响应头为 JSON 格式
    w.Header().Set("Content-Type", "application/json")

    // 解析 URL 参数中的 id
    idStr := r.URL.Query().Get("id")
    id, err := strconv.Atoi(idStr)
    if err != nil {
        // 处理无效 ID 的情况
        w.WriteHeader(http.StatusBadRequest)
        response := map[string]interface{}{
            "code":    -1,
            "message": "无效的用户 ID",
        }
        json.NewEncoder(w).Encode(response)
        return
    }

    // 创建 DeviceBasic 对象
    user := device.DeviceBasic{
        DeviceID: strconv.Itoa(id),
    }

    // 调用删除用户的函数
    db := device.DeleteDevice(user)
    if db.Error != nil {
        // 处理删除出错的情况
        w.WriteHeader(http.StatusInternalServerError)
        response := map[string]interface{}{
            "code":    -2,
            "message": "删除用户时出错",
        }
        json.NewEncoder(w).Encode(response)
        return
    }

    // 删除成功，返回响应
    w.WriteHeader(http.StatusOK)
    response := map[string]interface{}{
        "code":    0,
        "message": "删除用户成功！",
    }
    json.NewEncoder(w).Encode(response)
}